#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask扩展和服务实例
"""

from flask_cors import CORS
from flask_socketio import SocketIO
from config.tos_config import TOSConfig
from config.amap_config import AmapConfig
from services.asr_service import MinimalASR
from services.intelligent_command_service import IntelligentCommandService
from services.voice_control_service import VoiceControlService
from services.streaming_asr_service import StreamingASRService
from services.llm_client import LLMClient
from services.intent_classifier import IntentClassifier
from services.streaming_tts_service import StreamingTTSService, RealtimeTTSService
from services.amap_mcp_service import AmapMCPService
from services.amap_rest_service import AmapRestService
from services.text_to_images import TextToImageService

# Flask-SocketIO实例（将在create_app中初始化）
socketio = None

# 全局服务实例
tos_config = None
asr_service = None
command_service = None
voice_control_service = None
llm_client = None
intent_classifier = None
amap_service = None
amap_service_type = None
text_to_image_service = None

# WebSocket连接管理
connected_clients = set()

# 流式ASR会话管理
streaming_sessions = {}  # {client_id: {'asr_service': StreamingASRService, 'loop': asyncio.loop, 'task': asyncio.Task}}
streaming_audio_buffer = {}  # {client_id: [audio_chunks]}
streaming_audio_queues = {}  # {client_id: asyncio.Queue} - 音频数据队列

# 流式TTS会话管理
tts_sessions = {}  # {client_id: {'tts_service': StreamingTTSService, 'loop': asyncio.loop, 'task': asyncio.Task}}

# 自动TTS播报队列
auto_tts_queue = {}  # {client_id: [{'text': str, 'voice_type': str, ...}]}


def init_extensions(app):
    """
    初始化Flask扩展
    
    Args:
        app: Flask应用实例
    """
    global socketio
    
    # 配置CORS - 允许跨域请求
    CORS(app, 
         origins=['http://localhost:3001', 'http://127.0.0.1:3001'],
         methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
         allow_headers=['Content-Type', 'Authorization', 'Accept'],
         supports_credentials=True,
         max_age=3600)
    
    # 创建SocketIO实例
    socketio = SocketIO(
        app, 
        cors_allowed_origins=['http://localhost:3001', 'http://127.0.0.1:3001'],
        logger=False, 
        engineio_logger=False
    )
    
    return socketio


def init_services():
    """
    初始化所有业务服务
    """
    global tos_config, asr_service, command_service, voice_control_service
    global llm_client, intent_classifier, amap_service, amap_service_type
    global text_to_image_service
    
    # 创建TOS配置实例
    tos_config = TOSConfig()
    
    # 创建ASR服务实例
    asr_service = MinimalASR()
    
    # 创建智能指令处理服务实例
    command_service = IntelligentCommandService()
    
    # 创建语音控制服务实例
    voice_control_service = VoiceControlService(
        asr_service=asr_service,
        command_service=command_service
    )
    
    # 创建LLM客户端实例
    llm_client = LLMClient()
    
    # 创建意图分类器实例
    intent_classifier = IntentClassifier()
    
    # 初始化高德地图服务
    if AmapConfig.AMAP_ENABLED and AmapConfig.validate():
        try:
            if AmapConfig.USE_REST_API:
                # 使用REST API（推荐）
                amap_service = AmapRestService(api_key=AmapConfig.AMAP_API_KEY)
                amap_service_type = "REST API"
                print("✅ 高德地图REST API服务已启用")
            else:
                # 使用MCP服务
                amap_service = AmapMCPService(
                    api_key=AmapConfig.AMAP_API_KEY,
                    base_url=AmapConfig.AMAP_MCP_BASE_URL
                )
                amap_service_type = "MCP"
                print("✅ 高德地图MCP服务已启用")
        except Exception as e:
            print(f"⚠️  高德地图服务初始化失败: {str(e)}")
            print(f"   提示: MCP服务当前不可用，建议在config/amap_config.py中设置USE_REST_API=True")
            amap_service = None
            amap_service_type = None
    else:
        print("ℹ️  高德地图服务未启用（需要配置AMAP_API_KEY和AMAP_ENABLED=true）")
    
    # 初始化文生图服务
    try:
        text_to_image_service = TextToImageService()
        print("✅ 文生图服务已启用")
    except Exception as e:
        print(f"⚠️  文生图服务初始化失败: {str(e)}")
        text_to_image_service = None

